package com.demo.minicat;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * @author: lipan
 * @date: 2021/9/29 21:59
 */

public class StaticResourceUtils {


    //获取绝对路径 文件是放在类路径下
    public static String getAbsolutePath(String path){
        //用类加载拿 只能传"" 而且不带包路径就是classpath的根目录
        //用class去拿 传"/" 不带包路径 ""带包路径
        String absolutePath= Thread.currentThread().getContextClassLoader().getResource("").getPath();
        return absolutePath+path;
    }

    /**
     *
     * @param outputStream   输入流 将文件输出给浏览器
     * @param path 资源的uri
     * @throws Exception
     */
    public static void  printStaticResource(OutputStream outputStream,String path) throws Exception{
        String absolutePath = getAbsolutePath(path);
        FileInputStream fis = new FileInputStream(absolutePath);
        outputStream.write(HttpUtils.getHeader(HttpStatus.OK).getBytes());
        int len = 0;
        byte[] bytes = new byte[1024];
        while((len = fis.read(bytes))!=-1){
//            outputStream.write(new String(bytes).getBytes("utf-8"),0,len);
            outputStream.write(bytes,0,len);
        }

        outputStream.close();
        fis.close();
    }




}
